#!/usr/bin/env python3
import sys
from tree_printer import print_list_tree
from elftools.elf.elffile import ELFFile
from elftools.dwarf.die import DIE, AttributeValue
# from pprint import pprint


def process_file(file_path: str):
    print(f'Processing file: {file_path}')
    with open(file_path, 'rb') as f:
        elf_file = ELFFile(f)

        if not elf_file.has_dwarf_info():
            print('  file has no DWARF info')
            return

        # get_dwarf_info returns a DWARFInfo context object, which is the
        # starting point for all DWARF-based processing in pyelftools.
        dwarf_info = elf_file.get_dwarf_info()

        for CU in dwarf_info.iter_CUs():
            # DWARFInfo allows to iterate over the compile units contained in
            # the .debug_info section. CU is a CompileUnit object, with some
            # computed attributes (such as its offset in the section) and
            # a header which conforms to the DWARF standard. The access to
            # header elements is, as usual, via item-lookup.
            print('  Found a compile unit at offset %s, length %s' % (
                CU.cu_offset, CU['unit_length']))

            # Start with the top DIE, the root for this CU's DIE tree
            top_DIE: DIE = CU.get_top_DIE()
            print('    Top DIE with tag=%s' % top_DIE.tag)

            # We're interested in the filename...
            print('    name=%s' % top_DIE.get_full_path())

            # Display DIEs recursively starting with top_DIE
            tree = die_info_rec(top_DIE)
            # pprint(tree)
            print_list_tree(tree)


def die_info_rec(die: DIE):
    # print(indent_level + 'DIE tag=%s' % die.tag)
    #attrs = [die.tag,
    #         f'Size: {die.size}',
    #         f'Offset: {die.offset}',
    #         f'Abcode: {die.abbrev_code}',
    #         f'hasChld:{str(die.has_children)}',
    #         list(die.attributes.values())]
    children_tree = list(map(die_info_rec, die.iter_children()))
    die_str= repr(die) + '\n'
    return [die_str, children_tree] if children_tree else die_str


if __name__ == '__main__':
    for filename in sys.argv[1:]:
        process_file(filename)
